package com.xiaoyao.novel.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.xiaoyao.novel.common.Constant;
import com.xiaoyao.novel.pojo.Admin;

/**
 * 登录过滤器
 * 
 * @author 旷明爱
 * @date Dec 13, 2012 9:13:27 AM
 */
public class LoginFilter implements Filter {
	private static Logger logger = Logger.getLogger(JSPFilter.class);

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		boolean through = false;
		// logger.info("LoginFilter do filter start....");
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String uri = httpRequest.getRequestURI();
		logger.debug("验证登录 uri:[" + uri + "]");

		if (uri.contains("system/")) {
			// 验证登录
			HttpSession session = httpRequest.getSession();
			Admin user = (Admin) session.getAttribute(Constant.ADMIN_SESSION_KEY);
			// 权限验证.
			if (user == null) {
				through = false;
				logger.info("请登录!");
			}else {
				through=true;
			}
		}
		if (through) {
			chain.doFilter(request, response);
		} else {
			httpResponse.sendRedirect("../index.html");
		}
	}

	public void destroy() {
	}

	public void init(FilterConfig arg0) throws ServletException {
	}
}